﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media.Imaging;

namespace PhonePcFileTransfer.Models
{
    public class FileInfoModel
    {
        public string Path { get; set; }
        public string Name => System.IO.Path.GetFileName(Path);
        public string Size => FormatSize(new FileInfo(Path).Length);
        public BitmapImage Icon => GetFileIcon();

        private string FormatSize(long bytes)
        {
            if (bytes < 1024)
                return $"{bytes} B";
            else if (bytes < 1048576)
                return $"{(bytes / 1024.0).ToString("0.0")} KB";
            else if (bytes < 1073741824)
                return $"{(bytes / 1048576.0).ToString("0.0")} MB";
            else
                return $"{(bytes / 1073741824.0).ToString("0.0")} GB";
        }

        private BitmapImage GetFileIcon()
        {
            try
            {
                // 获取系统文件图标
                var icon = System.Drawing.Icon.ExtractAssociatedIcon(Path);
                using (var stream = new MemoryStream())
                {
                    icon.ToBitmap().Save(stream, System.Drawing.Imaging.ImageFormat.Png);
                    stream.Position = 0;

                    var bitmapImage = new BitmapImage();
                    bitmapImage.BeginInit();
                    bitmapImage.StreamSource = stream;
                    bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
                    bitmapImage.EndInit();
                    return bitmapImage;
                }
            }
            catch
            {
                // 返回默认图标
                return new BitmapImage(new Uri("pack://application:,,,/Images/file_icon.png"));
            }
        }
    }
}
